<template>
  <div class="page-wrapper">
    <div class="page-header">
      <span class="text-primary font-bold">待办任务</span>
    </div>

    <div class="page-content">
      <!-- 搜索表单 -->
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="流程名称">
          <el-input v-model="searchForm.name" placeholder="请输入流程名称" clearable />
        </el-form-item>
        <el-form-item label="流程分类">
          <el-select v-model="searchForm.category" placeholder="请选择流程分类" clearable>
            <el-option
              v-for="item in categoryOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="用户编号">
          <el-input v-model="searchForm.userId" placeholder="请输入用户编号" clearable />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 表格区域 -->
      <div class="table-wrapper">
        <el-table :data="tableData" v-loading="loading">
          <el-table-column
            prop="processInstanceName"
            label="流程名称"
            width="150"
            show-overflow-tooltip
          />
          <el-table-column prop="name" label="任务名称" width="150" show-overflow-tooltip />
          <el-table-column prop="assignee" label="办理人" width="160" show-overflow-tooltip />
          <el-table-column prop="createTime" label="创建时间" width="180" show-overflow-tooltip />
          <el-table-column prop="status" label="状态" width="100">
            <template #default="{ row }">
              <el-tag :type="getStatusType(row.status)">{{ getStatusLabel(row.status) }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" min-width="200" fixed="right">
            <template #default="{ row }">
              <template v-if="row.buttonConfigs && row.buttonConfigs.length && dictReady">
                <el-button
                  v-for="btn in sortedButtons(row.buttonConfigs)"
                  :key="btn.id"
                  :type="getButtonTagType(btn.type)"
                  :class="['task-button', { 'button-disabled': !btn.enabled }]"
                  :style="{
                    backgroundColor: btn.enabled ? getButtonBgColor(btn.type) : '',
                    color: btn.enabled ? getButtonTextColor(btn.type) : '',
                    borderColor: btn.enabled ? getButtonBorderColor(btn.type) : '',
                  }"
                  link
                  :disabled="!btn.enabled"
                  @click="handleTaskAction(row, btn)"
                >
                  {{ btn.name }}
                </el-button>
              </template>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 分页区域 -->
      <div class="pagination-wrapper">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 30, 50]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <!-- API测试器对话框 -->
    <el-dialog
      v-model="apiTesterVisible"
      title="处理任务"
      width="50%"
      destroy-on-close
      :modal-append-to-body="false"
      class="task-operation-dialog"
    >
      <ApiTester
        url="/workflow/task/operate"
        method="POST"
        :initial-params="getInitialParams()"
        @success="handleOperateSuccess"
      />
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="apiTesterVisible = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts" name="TodoList">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import type { TaskVo, ButtonConfig } from '@/types/flow'
import { getTaskTodoPage } from '@/api/flow/task'
import { useDictOptions } from '@/utils/dict'
import ApiTester from '@/components/ApiTester/index.vue'

// 搜索表单
const searchForm = reactive({
  name: '',
  category: '',
  userId: '', // 当前用户ID，需要从用户状态获取
})

// 表格数据
const tableData = ref<TaskVo[]>([])
const loading = ref(false)

// 分页
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 流程分类选项
const { options: categoryOptions } = useDictOptions('bpmn_category')

// 加载任务状态字典
const { options: taskStatusOptions } = useDictOptions('task_status')

// 加载任务操作字典
const { options: taskOperationOptions, ready: dictReady } = useDictOptions('task_operation')

// API测试器相关
const apiTesterVisible = ref(false)
const currentTask = ref<TaskVo>()
const currentButton = ref<ButtonConfig>()

// 获取初始请求参数
const getInitialParams = () => {
  const baseParams = {
    userId: currentTask.value?.assignee,
    taskId: currentTask.value?.id,
    operation: currentButton.value?.type,
    variables: {
      applicant: '李四',
      amount: 2000,
      description: '报销申请111',
    },
  }

  // 根据不同的操作类型添加特定参数
  switch (currentButton.value?.type) {
    case 'agree':
      return JSON.stringify(
        {
          ...baseParams,
          comment: '同意操作',
        },
        null,
        2,
      )
    case 'reject':
      return JSON.stringify(
        {
          ...baseParams,
          comment: '拒绝操作',
        },
        null,
        2,
      )
    case 'delegate':
      return JSON.stringify(
        {
          ...baseParams,
          comment: '委派操作',
          delegateUserId: '', // 需要指定委派的用户ID
        },
        null,
        2,
      )
    case 'transfer':
      return JSON.stringify(
        {
          ...baseParams,
          comment: '转办操作',
          transferUserId: '', // 需要指定转办的用户ID
        },
        null,
        2,
      )
    case 'return':
      return JSON.stringify(
        {
          ...baseParams,
          comment: '退回操作',
          returnTarget: '', // 需要指定退回的目标节点ID
        },
        null,
        2,
      )
    case 'returnToStart':
      return JSON.stringify(
        {
          ...baseParams,
          comment: '退回到发起人',
        },
        null,
        2,
      )
    case 'rejectBack':
      return JSON.stringify(
        {
          ...baseParams,
          comment: '驳回结束',
        },
        null,
        2,
      )
    case 'addSign':
      return JSON.stringify(
        {
          ...baseParams,
          addSignUsers: [], // 需要指定加签的用户ID列表
          comment: '加签', // 加签说明
        },
        null,
        2,
      )
    case 'terminate':
      return JSON.stringify(
        {
          ...baseParams,
          comment: '终止', // 终止原因
        },
        null,
        2,
      )
    case 'multi_agree':
      return JSON.stringify(
        {
          ...baseParams,
          comment: '同意（会签）', // 终止原因
        },
        null,
        2,
      )
    case 'multi_refuse':
      return JSON.stringify(
        {
          ...baseParams,
          comment: '拒绝（会签）', // 终止原因
        },
        null,
        2,
      )
    case 'multi_abstain':
      return JSON.stringify(
        {
          ...baseParams,
          comment: '弃权（会签）', // 终止原因
        },
        null,
        2,
      )
    default:
      return JSON.stringify(baseParams, null, 2)
  }
}

// 获取状态标签
const getStatusLabel = (status: string) => {
  const option = taskStatusOptions.value.find((opt) => opt.value === status)
  return option?.label || status
}

// 获取状态标签类型
const getStatusType = (status: string) => {
  const map: Record<string, string> = {
    running: 'primary',
    approve: 'success',
    reject: 'danger',
    cancel: 'info',
    return: 'warning',
    approving: 'success',
    waiting: 'warning',
  }
  return map[status] || 'info'
}

// 加载表格数据
const loadTableData = async () => {
  loading.value = true
  try {
    const params = {
      pageNo: currentPage.value,
      pageSize: pageSize.value,
      ...searchForm,
    }
    const res = await getTaskTodoPage(params)
    if (res.data) {
      tableData.value = res.data.list || []
      total.value = res.data.total || 0
    }
  } catch (error) {
    console.error('获取待办任务列表失败:', error)
    ElMessage.error('获取待办任务列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  currentPage.value = 1
  loadTableData()
}

// 重置搜索
const resetSearch = () => {
  searchForm.name = ''
  searchForm.category = ''
  searchForm.userId = ''
  handleSearch()
}

// 分页处理
const handleSizeChange = (val: number) => {
  pageSize.value = val
  loadTableData()
}

const handleCurrentChange = (val: number) => {
  currentPage.value = val
  loadTableData()
}

// 获取按钮标签类型
const getButtonTagType = (type: string) => {
  if (!taskOperationOptions.value) return 'info'
  const option = taskOperationOptions.value.find((opt) => opt.value === type)
  if (!option?.config) return 'info'
  try {
    const config = JSON.parse(option.config)
    return config.tagType || 'info'
  } catch {
    return 'info'
  }
}

// 获取按钮背景色
const getButtonBgColor = (type: string) => {
  if (!taskOperationOptions.value) return ''
  const option = taskOperationOptions.value.find((opt) => opt.value === type)
  if (!option?.config) return ''
  try {
    const config = JSON.parse(option.config)
    return config.bgColor || ''
  } catch {
    return ''
  }
}

// 获取按钮文字颜色
const getButtonTextColor = (type: string) => {
  if (!taskOperationOptions.value) return ''
  const option = taskOperationOptions.value.find((opt) => opt.value === type)
  if (!option?.config) return ''
  try {
    const config = JSON.parse(option.config)
    return config.textColor || ''
  } catch {
    return ''
  }
}

// 获取按钮边框颜色
const getButtonBorderColor = (type: string) => {
  if (!taskOperationOptions.value) return ''
  const option = taskOperationOptions.value.find((opt) => opt.value === type)
  if (!option?.config) return ''
  try {
    const config = JSON.parse(option.config)
    return config.borderColor || ''
  } catch {
    return ''
  }
}

// 按钮排序
const sortedButtons = (buttons: ButtonConfig[]) => {
  return [...buttons].sort((a, b) => a.sort - b.sort)
}

// 处理任务按钮点击
const handleTaskAction = async (task: TaskVo, button: ButtonConfig) => {
  currentTask.value = task
  currentButton.value = button
  apiTesterVisible.value = true
}

// 处理操作成功
const handleOperateSuccess = () => {
  // 刷新列表
  loadTableData()
}

// 初始化加载数据
onMounted(() => {
  loadTableData()
})
</script>

<style scoped>
.todo-list {
  padding: 20px;
}

.search-form {
  margin-bottom: 20px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

/* 添加按钮样式 */
:deep(.el-button) {
  padding: 4px 8px;
  margin-left: 0;
  margin-right: 8px;
}

:deep(.el-button:last-child) {
  margin-right: 0;
}

/* 任务按钮样式 */
:deep(.task-button) {
  height: 24px;
  padding: 0 12px;
  margin: 0 4px;
  border-radius: 4px;
  font-size: 12px;
  font-weight: 500;
  transition: all 0.3s;
  border: 1px solid transparent;
}

:deep(.task-button:first-child) {
  margin-left: 0;
}

:deep(.task-button:last-child) {
  margin-right: 0;
}

:deep(.task-button:hover) {
  opacity: 0.8;
  transform: translateY(-1px);
}

:deep(.button-disabled) {
  opacity: 0.6;
  cursor: not-allowed;
}

:deep(.button-disabled:hover) {
  transform: none;
}

/* 确保表格单元格内容垂直居中 */
:deep(.el-table__cell) {
  .cell {
    display: flex;
    align-items: center;
    flex-wrap: wrap;
    gap: 4px;
  }
}

:deep(.task-operation-dialog) {
  margin-top: 5vh !important;
}

:deep(.task-operation-dialog .el-dialog__body) {
  max-height: 70vh;
  overflow-y: auto;
  padding: 0;
}
</style>
